package com.atguigu.mymvc.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.sql.Timestamp;
import java.time.LocalDateTime;

public class ClassUtil {

    public static Object createInstance(String entityClassName){
        try {
            return Class.forName(entityClassName).getDeclaredConstructor().newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null ;
    }

    public static void setProperty(Object instance , String propertyName, Object propertyValue){
        Class<?> aClass = instance.getClass();
        try {
            Field field = aClass.getDeclaredField(propertyName);
            field.setAccessible(true);
            String fieldType = field.getType().getName() ;
            if("java.util.Date".equals(fieldType)) {
                String typeName = propertyValue.getClass().getTypeName();
                if("java.time.LocalDateTime".equals(typeName)){
                    propertyValue = Timestamp.valueOf((LocalDateTime) propertyValue);
                }
            }
            field.set(instance,propertyValue);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
